package top.yueyazhui.vhr.controller.HrInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import top.yueyazhui.vhr.bean.Response;
import top.yueyazhui.vhr.model.Hr;
import top.yueyazhui.vhr.service.HrService;

import java.util.Map;

@RestController
@RequestMapping("/hr/info")
@Api(tags = "当前用户信息")
public class HrInfoController {

    @Autowired
    HrService hrService;

    @GetMapping("/")
    @ApiOperation(value = "获取当前用户信息", notes = "获取当前用户信息")
    public Hr getCurrentHr(Authentication authentication) {
        return ((Hr) authentication.getPrincipal());
    }

    @PutMapping("/")
    @ApiOperation(value = "编辑当前用户信息", notes = "编辑当前用户信息")
    public Response update(@RequestBody Hr hr, Authentication authentication) {
        if(hrService.update(hr) == 1) {
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(hr, authentication.getCredentials(), authentication.getAuthorities()));
            return Response.success("更新成功！");
        }
        return Response.error("更新失败！");
    }

    @PutMapping("/pwd")
    @ApiOperation(value = "更新当前用户密码", notes = "更新当前用户密码")
    public Response updatePassword(@RequestBody Map<String, Object> pwdInfo) {

        String oldPass = (String) pwdInfo.get("oldPass");
        String pass = (String) pwdInfo.get("pass");
        String checkPass = (String) pwdInfo.get("checkPass");
        Integer userId = (Integer) pwdInfo.get("id");

        Integer result = hrService.updatePassword(oldPass, pass, checkPass, userId);

        if(result.equals(1)) {
            return Response.success("更新成功，请重新登录！");
        }
        if(result.equals(-1)) {
            return Response.error("更新失败，旧密码输入不正确！");
        }
        if(result.equals(-2)) {
            return Response.error("更新失败，密码不符合规范；密码规范：3个字符或3个字符以上，字符范围包括数字、大小写字母和英文状态特殊字符!@#$%^&*");
        }
        if(result.equals(-3)) {
            return Response.error("更新失败，两次输入密码不一致！");
        }
        return Response.error("更新失败！");
    }
}
